<template>
  <div class="models-page">
    <div class="models-header">
      <h2>模型管理</h2>
      <t-button theme="primary" @click="handleCreateModel">
        <template #icon>
          <t-icon name="add" />
        </template>
        新建模型
      </t-button>
    </div>

    <t-table
      :data="filteredModels"
      :columns="columns"
      row-key="id"
      size="medium"
      hover
      :loading="loading"
    >
      <template #type="{ row }">
        <t-tag :theme="getTypeTheme(row.type)" variant="light">
          {{ getTypeLabel(row.type) }}
        </t-tag>
      </template>

      <template #status="{ row }">
        <t-tag :theme="getStatusTheme(row.status)" variant="light">
          {{ getStatusLabel(row.status) }}
        </t-tag>
        <t-tag
          v-if="row.is_default"
          theme="primary"
          variant="light"
          size="small"
          style="margin-left: 8px"
        >
          默认
        </t-tag>
      </template>

      <template #description="{ row }">
        <div class="description-text">{{ row.description || "暂无描述" }}</div>
      </template>

      <template #source="{ row }">
        <span>{{ row.source === "local" ? "本地" : "云端" }}</span>
      </template>

      <template #op="{ row }">
        <t-space size="small">
          <t-button
            size="small"
            :theme="row.is_default ? 'default' : 'primary'"
            :variant="row.is_default ? 'outline' : 'base'"
            @click="handleSetDefault(row)"
            :disabled="row.is_default"
          >
            {{ row.is_default ? "默认" : "设为默认" }}
          </t-button>
          <t-button size="small" variant="outline" @click="handleEditModel(row)"
            >编辑</t-button
          >
          <t-popconfirm
            content="确认删除该模型？"
            @confirm="handleDeleteModel(row)"
          >
            <t-button size="small" theme="danger" variant="text">删除</t-button>
          </t-popconfirm>
        </t-space>
      </template>
    </t-table>


    <!-- 模型表单对话框 -->
    <model-form-dialog
      v-model:visible="formDialogVisible"
      :model-data="currentModel"
      :is-edit="isEdit"
      @success="handleFormSuccess"
    />

    <!-- 删除确认对话框 -->
    <t-dialog
      v-model:visible="deleteDialogVisible"
      header="确认删除"
      :confirm-btn="{ theme: 'danger', content: '删除' }"
      @confirm="handleConfirmDelete"
    >
      <p>确定要删除模型 "{{ deleteModel?.name }}" 吗？此操作不可恢复。</p>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { MessagePlugin } from "tdesign-vue-next";
import type { ModelItem, ModelType, ModelStatus } from "@/types/models";
import { modelsApi } from "@/api/models";
import ModelFormDialog from "./components/ModelFormDialog.vue";

// 响应式数据
const loading = ref(false);
const modelList = ref<ModelItem[]>([]);
const searchKeyword = ref("");
const filterType = ref("all");
const filterStatus = ref("all");

// 表格列定义
const columns = [
  { colKey: "name", title: "名称", width: 200 },
  { colKey: "type", title: "类型", width: 120 },
  { colKey: "status", title: "状态", width: 150 },
  { colKey: "description", title: "描述", width: 300 },
  { colKey: "source", title: "来源", width: 10 },
  { colKey: "created_at", title: "创建时间", width: 180 },
  { colKey: "op", title: "操作", width: 200 },
];


// 对话框状态
const formDialogVisible = ref(false);
const deleteDialogVisible = ref(false);
const isEdit = ref(false);
const currentModel = ref<ModelItem | null>(null);
const deleteModel = ref<ModelItem | null>(null);

// 计算属性
const filteredModels = computed(() => {
  return modelList.value;
});

// 获取模型列表
const fetchModelList = async () => {
  try {
    loading.value = true;
    
    // 获取所有数据，然后在前端进行过滤
    const response = await modelsApi.getModelsList();
    
    if (response.success) {
      // 先应用过滤条件
      let filtered = response.data;
      
      // 按类型过滤
      if (filterType.value !== "all") {
        filtered = filtered.filter((model) => model.type === filterType.value);
      }
      
      // 按状态过滤
      if (filterStatus.value !== "all") {
        filtered = filtered.filter((model) => model.status === filterStatus.value);
      }
      
      // 按关键词搜索
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase();
        filtered = filtered.filter(
          (model) =>
            model.name.toLowerCase().includes(keyword) ||
            model.description?.toLowerCase().includes(keyword)
        );
      }
      
      // 更新modelList为过滤后的数据（不分页）
      modelList.value = filtered;
    } else {
      MessagePlugin.error("获取模型列表失败");
    }
  } catch (error: any) {
    console.error("获取模型列表失败:", error);
    // 检查是否为401认证错误
    if (error.status === 401 || (error.response && error.response.status === 401)) {
      MessagePlugin.error("API认证失败，请检查API Key配置");
    } else {
      MessagePlugin.error("获取模型列表失败: " + (error.message || error.msg || "未知错误"));
    }
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  fetchModelList();
};

// 处理筛选变化
const handleFilterChange = () => {
  fetchModelList();
};

// 处理创建模型
const handleCreateModel = () => {
  isEdit.value = false;
  currentModel.value = null;
  formDialogVisible.value = true;
};

// 处理编辑模型
const handleEditModel = (model: ModelItem) => {
  isEdit.value = true;
  currentModel.value = { ...model };
  formDialogVisible.value = true;
};

// 处理删除模型
const handleDeleteModel = (model: ModelItem) => {
  deleteModel.value = model;
  deleteDialogVisible.value = true;
};

// 确认删除
const handleConfirmDelete = async () => {
  if (!deleteModel.value) return;

  try {
    const response = await modelsApi.deleteModel(
      deleteModel.value.id
    );
    if (response.success) {
      MessagePlugin.success("删除成功");
      await fetchModelList();
    } else {
      MessagePlugin.error("删除失败");
    }
 } catch (error: any) {
    console.error("删除模型失败:", error);
    // 检查是否为401认证错误
    if (error.status === 401 || (error.response && error.response.status === 401)) {
      MessagePlugin.error("API认证失败，请检查API Key配置");
    } else {
      MessagePlugin.error("删除失败: " + (error.message || error.msg || "未知错误"));
    }
 } finally {
    deleteDialogVisible.value = false;
    deleteModel.value = null;
  }
};

// 设为默认模型
const handleSetDefault = async (model: ModelItem) => {
  try {
    const response = await modelsApi.updateModel(model.id, {
      ...model,
      is_default: true,
    });
    if (response.success) {
      MessagePlugin.success("设置成功");
      await fetchModelList();
    } else {
      MessagePlugin.error("设置失败");
    }
 } catch (error: any) {
    console.error("设置默认模型失败:", error);
    // 检查是否为401认证错误
    if (error.status === 401 || (error.response && error.response.status === 401)) {
      MessagePlugin.error("API认证失败，请检查API Key配置");
    } else {
      MessagePlugin.error("设置失败: " + (error.message || error.msg || "未知错误"));
    }
 }
};

// 处理表单成功
const handleFormSuccess = async () => {
  formDialogVisible.value = false;
  await fetchModelList();
};

// 获取模型图标
const getModelIcon = (type: ModelType) => {
  const iconMap = {
    KnowledgeQA: "chat",
    Embedding: "layers",
    Rerank: "sort",
  };
  return iconMap[type] || "setting";
};

// 获取类型标签颜色
const getTypeTheme = (type: ModelType) => {
  const themeMap = {
    KnowledgeQA: "primary",
    Embedding: "success",
    Rerank: "warning",
  };
  return themeMap[type] || "default";
};

// 获取状态标签颜色
const getStatusTheme = (status: ModelStatus) => {
  const themeMap = {
    active: "success",
    downloading: "warning",
    inactive: "default",
  };
  return themeMap[status] || "default";
};

// 获取类型标签文本
const getTypeLabel = (type: ModelType) => {
  const labelMap = {
    KnowledgeQA: "对话模型",
    Embedding: "嵌入模型",
    Rerank: "排序模型",
  };
  return labelMap[type] || type;
};

// 获取状态标签文本
const getStatusLabel = (status: ModelStatus) => {
  const labelMap = {
    active: "活跃",
    downloading: "下载中",
    inactive: "未激活",
  };
  return labelMap[status] || status;
};

// 格式化时间
const formatTime = (time: string) => {
  return new Date(time).toLocaleString();
};

// 生命周期
onMounted(() => {
  fetchModelList();
});
</script>

<style scoped lang="less">
.models-page {
  padding: 20px;
  background: #fff;
  margin: 0 20px 0 20px;
  height: calc(100vh);
  overflow-y: auto;
  box-sizing: border-box;
  flex: 1;

  .models-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 600;
    }
  }

  .description-text {
    color: #000000e6;
    font-size: 14px;
  }

}
</style>
